<template>
  <view class="login">
    <view class="content">
      <!-- 头部logo -->
      <view class="header">
        <image :src="logoImage"></image>
      </view>
      <!-- 主体表单 -->
      <view class="main">
        <wInput
          v-model="loginForm.username"
          type="text"
          maxlength="20"
          placeholder="用户名"
        ></wInput>
        <wInput
          v-model="loginForm.password"
          type="password"
          maxlength="20"
          placeholder="密码"
        ></wInput>
        <view class="form-code w-full flex items-center">
          <wInput
            class="form-code-input flex-1"
            v-model="loginForm.code"
            type="code"
            maxlength="11"
            placeholder="验证码"
          ></wInput>
          <image class="form-code-img" :src="captchaSrc" alt="验证码" @click="getCaptcha">
        </view>
        
      </view>
      <wButton
        text="登录"
        :rotate="isRotate"
        @click.native="startLogin()"
        class="wbutton"
        bg-color="#0d376b"
      ></wButton>

      <!-- 其他登录 -->
      <view class="other_login cuIcon">
        <view class="login_icon">
          <view style="margin-bottom: -20upx" class="cuIcon-weixin wechat_color" @tap="login_weixin"></view>
          <text style="font-size: 30upx;">微信登录</text>
        </view>
      </view>

      <!-- 底部信息 -->
      <!-- <view class="footer">
        <navigator url="forget" open-type="navigate">找回密码</navigator>
        <text>|</text>
        <navigator url="register" open-type="navigate">注册账号</navigator>
      </view> -->
    </view>
  </view>
</template>

<script>
var _this;
import wInput from "@/components/watch-login/watch-input.vue"; //input
import wButton from "@/components/watch-login/watch-button.vue"; //button
// import cookies from 'weapp-cookie'
export default {
  data() {
    return {
      //logo图片 base64
      logoImage: "",
      isRotate: false, //是否加载旋转
      loginForm: {
        username: '',
        password: '',
        userFlag: 'A',
        openId: '', // 钉钉openid
        code: '', // 验证码
        uuid: '', // 验证码对应的随机uuid
      },
      captchaSrc: ''
    };
  },
  components: {
    wInput,
    wButton,
  },
  onShareAppMessage() {
    console.log("分享小程序");
  },
  mounted() {
    _this = this;
    this.fetchSystemInfo()
    this.getCaptcha()
    //this.isLogin();
  },
  methods: {
    async fetchSystemInfo() {
      const { result, code } = await this.$request('/api/system/info')
      if (code === 1) {
        this.logoImage = result.logoPath
      }
    },
    async getCaptcha() {
      const {result, code} = await this.$request('/api/captcha')
      if (code === 1) {
        this.loginForm.uuid = result.uuid
        this.captchaSrc = result.img
      }
    },
    isLogin() {
      //判断缓存中是否登录过，直接登录
      // try {
      // 	const value = uni.getStorageSync('setUserData');
      // 	if (value) {
      // 		//有登录信息
      // 		console.log("已登录用户：",value);
      // 		_this.$store.dispatch("setUserData",value); //存入状态
      // 		uni.reLaunch({
      // 			url: '../../../pages/index',
      // 		});
      // 	}
      // } catch (e) {
      // 	// error
      // }
    },
    startLogin() {
      //登录
      if (this.isRotate) {
        //判断是否加载中，避免重复点击请求
        return false;
      }
      if (this.loginForm.username.length == "") {
        uni.showToast({
          icon: "none",
          position: "bottom",
          title: "用户名不能为空",
        });
        return;
      }
      if (this.loginForm.password.length < 3) {
        uni.showToast({
          icon: "none",
          position: "bottom",
          title: "密码不正确",
        });
        return;
      }

      _this.isRotate = true;
      this.$request('/api/shiro/login', this.loginForm, 'POST').then(res => {
        if(res.code === 1) {
          uni.showToast({title: '登录成功'})
          uni.setStorageSync('userData', res.result); //存入缓存
          setTimeout(() => {
            uni.navigateTo({url: '/pages/project/index'})
          }, 1000)
        }
         _this.isRotate = false;
      })

      // uni.showLoading({
      // 	title: '登录中'
      // });
      // getLogin()
      // .then(res => {
      // 	//console.log(res)
      // 	//简单验证下登录（不安全）
      // 	if(_this.loginForm.username==res.data.username && _this.loginForm.password==res.data.password){
      // 		let userdata={
      // 			"username":res.data.username,
      // 			"nickname":res.data.nickname,
      // 			"accesstoken":res.data.accesstoken,
      // 		} //保存用户信息和accesstoken
      // 		_this.$store.dispatch("setUserData",userdata); //存入状态
      // 		try {
      // 			uni.setStorageSync('setUserData', userdata); //存入缓存
      // 		} catch (e) {
      // 			// error
      // 		}
      // 		uni.showToast({
      // 			icon: 'success',
      // 			position: 'bottom',
      // 			title: '登录成功'
      // 		});
      // 		uni.reLaunch({
      // 			url: '../../../pages/index',
      // 		});
      // 	}else{
      // 		_this.loginForm.password=""
      // 		uni.showToast({
      // 			icon: 'error',
      // 			position: 'bottom',
      // 			title: '账号或密码错误，账号admin密码admin'
      // 		});
      // 	}
      // 	uni.hideLoading();
      // }).catch(err => {
      // 	uni.hideLoading();
      // })
    },
    login_weixin() {
      //微信登录
      uni.showToast({
        icon: 'loading',
      })
      const self = this
      uni.login({
        provider: 'weixin',
        // scopes: 'auth_base', // auth_base（静默授权）/ auth_user（主动授权）
        async success(loginRes) {
          const authResult = loginRes.authResult
          const authCode = loginRes.code
          const errMsg = loginRes.errMsg
          console.log('# AuthResult: ', authResult)
          console.log('# AuthCode: ', authCode)
          console.log('# ErrMsg: ', errMsg)
          const { result, message, code } = await self.$request(
            '/api/shiro/wx-login',
            {
              code: authCode,
            },
            'GET',
          )
          if (code === 1) {
            uni.showToast({
              icon: 'success',
              title: '登录成功',
            })
            uni.setStorageSync('userData', result); //存入缓存
            setTimeout(() => {
              uni.navigateTo({url: '/pages/project/index'})
            }, 1000)
          } else {
            uni.showToast({
              icon: 'none',
              title: message,
              duration: 3500,
            })
          }
        },
        fail(err) {
          reject()
          uni.showToast({
            icon: 'none',
            title: '授权失败!',
          })
          uni.hideLoading()
        },
      })
    },
    login_github() {
      //github登录
      uni.showToast({
        icon: "none",
        position: "bottom",
        title: "...",
      });
    },
  },
};
</script>

<style>
@import url("../../components/watch-login/css/icon.css");
@import url("./css/main.css");
</style>
